<template>
  <view class="container">
    <!-- 购物车为空时的提示 -->
    <view class="empty-cart" v-if="cartList.length === 0">
      <image class="empty-image" src="/static/images/empty-cart.png" mode="aspectFit"></image>
      <text class="empty-text">购物车还是空的</text>
      <button class="go-shopping" @click="goShopping">去逛逛</button>
    </view>
    
    <!-- 购物车商品列表 -->
    <view class="cart-list" v-else>
      <view class="cart-item" v-for="(item, index) in cartList" :key="item.id">
        <view class="checkbox">
          <checkbox 
            :checked="item.selected" 
            :disabled="item.status === '1'"
            @tap="toggleSelect(item)"
          />
        </view>
        <image class="goods-image" :src="item.image" mode="aspectFill" @tap="goToDetail(item)"></image>
        
        <view class="goods-info">
          <view class="goods-detail">
            <view class="goods-name">
              {{item.name}}
              <text v-if="item.status === '1'" class="status-tag off-shelf">已下架</text>
            </view>
            <view class="goods-spec">{{item.specText}}</view>
            <view class="price-quantity">
              <text class="price">¥{{item.price}}</text>
              <view class="quantity-control" v-if="item.status === '0'">
                <uni-number-box 
                  v-model="item.quantity"
                  :min="1"
                  :max="item.stock"
                  @change="(value) => handleQuantityChange(value, index)"
                ></uni-number-box>
              </view>
              <view v-else class="invalid-tip">商品已下架</view>
            </view>
          </view>
        </view>
        
        <text class="delete-btn" @tap="handleDelete(index)">×</text>
      </view>
    </view>
    
    <!-- 底部结算栏 -->
    <view class="footer" v-if="cartList.length > 0">
      <checkbox-group class="select-all" @change="handleSelectAll">
        <checkbox :checked="isAllSelected" :color="themeColor">全选</checkbox>
      </checkbox-group>
      
      <view class="total-box">
        <view class="price-detail">
          <text>合计：</text>
          <text class="total-price">¥{{totalPrice}}</text>
        </view>
        <text class="selected-count">已选{{selectedCount}}件</text>
      </view>
      
      <button class="checkout-btn" :disabled="selectedCount === 0" @tap="submitOrder">
        结算({{selectedCount}})
      </button>
    </view>
  </view>
</template>

<script>
import { userApi } from '@/api'
import { useCartStore } from '@/store'
import { storeToRefs } from 'pinia'

export default {
  data() {
    return {
      themeColor: '#4caf50' // 主题色
    }
  },
  setup() {
    const cartStore = useCartStore()
    const { cartList, loading } = storeToRefs(cartStore)
    
    return {
      cartStore,
      cartList,
      loading
    }
  },
  computed: {
    // 是否全选
    isAllSelected() {
      return this.cartList.length > 0 && this.cartList.every(item => item.selected)
    },
    // 选中的商品数量
    selectedCount() {
      return this.cartList.filter(item => item.selected).length
    },
    // 总价
    totalPrice() {
      return this.cartList
        .filter(item => item.selected && item.status === '0')
        .reduce((total, item) => total + item.price * item.quantity, 0)
        .toFixed(2)
    }
  },
  onShow() {
    this.loadCartList()
  },
  methods: {
    // 加载购物车数据
    async loadCartList() {
      await this.cartStore.fetchCartList()
    },
    
    // 选择单个商品
    async handleItemSelect(e, index) {
      try {
        const item = this.cartList[index]
        const selected = e.detail.value.length > 0
        // TODO: 调用接口更新选中状态
        
        // 更新本地状态
        this.cartList[index].selected = selected
        this.cartStore.calculateTotal()
      } catch (error) {
        console.error('更新商品选中状态失败:', error)
        uni.showToast({
          title: '更新商品选中状态失败',
          icon: 'none'
        })
      }
    },
    
    // 全选/取消全选
    async handleSelectAll(e) {
      try {
        const selected = e.detail.value.length > 0
        // TODO: 调用接口更新全选状态
        
        // 更新本地状态
        this.cartList.forEach(item => {
          // 只选中未下架的商品
          if (item.status === '0') {
            item.selected = selected
          }
        })
        this.cartStore.calculateTotal()
      } catch (error) {
        console.error('更新全选状态失败:', error)
        uni.showToast({
          title: '更新全选状态失败',
          icon: 'none'
        })
      }
    },
    
    // 修改商品数量
    async handleQuantityChange(value, index) {
      try {
        const item = this.cartList[index]
        await this.cartStore.updateGoodsQuantity(item.id, value)
      } catch (error) {
        // 错误已在 store 中处理
      }
    },
    
    // 删除商品
    async handleDelete(index) {
      uni.showModal({
        title: '提示',
        content: '确定要删除这个商品吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const item = this.cartList[index]
              await this.cartStore.deleteCartItem(item.id)
            } catch (error) {
              // 错误已在 store 中处理
            }
          }
        }
      })
    },
    
    // 结算
    submitOrder() {
      // 获取选中的商品
      const selectedItems = this.cartList.filter(item => item.selected)
      if (selectedItems.length === 0) {
        uni.showToast({
          title: '请选择要结算的商品',
          icon: 'none'
        })
        return
      }

      // 构造订单数据
      const orderData = selectedItems.map(item => ({
        cartId: item.id, // 购物车ID
        productId: item.productId,
        productName: item.name,
        skuId: item.skuId,
        quantity: item.quantity,
        price: item.price,
        specifications: item.specText, // 直接使用规格文本，不做转换
        image: item.image
      }))
      
      // 跳转到确认订单页
      uni.navigateTo({
        url: `/pages/order/confirm/index?orderData=${encodeURIComponent(JSON.stringify(orderData))}&type=cart`
      })
    },
    
    // 跳转到商品详情
    goToDetail(item) {
      uni.navigateTo({
        url: `/pages/goods/detail/index?id=${item.productId}`
      })
    },
    
    // 去购物
    goShopping() {
      uni.switchTab({
        url: '/pages/goods/list/index'
      })
    },
    
    // 切换商品选中状态
    async toggleSelect(item) {
      try {
        // TODO: 调用接口更新选中状态
        
        // 更新本地状态
        const index = this.cartList.findIndex(i => i.id === item.id)
        if (index > -1) {
          this.cartList[index].selected = !this.cartList[index].selected
          this.cartStore.calculateTotal()
        }
      } catch (error) {
        console.error('更新商品选中状态失败:', error)
        uni.showToast({
          title: '更新商品选中状态失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style>
.container {
  min-height: 100vh;
  background: #f8f8f8;
  padding-bottom: 120rpx;
}

/* 空购物车样式 */
.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 200rpx;
}

.empty-image {
  width: 240rpx;
  height: 240rpx;
  margin-bottom: 40rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 40rpx;
}

.go-shopping {
  width: 240rpx;
  height: 80rpx;
  line-height: 80rpx;
  background: var(--primary-color);
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
}

/* 购物车列表样式 */
.cart-list {
  padding: 20rpx;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  position: relative;
}

.goods-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
  margin: 0 20rpx;
}

.goods-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.goods-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
  display: flex;
  align-items: center;
}

.goods-spec {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 20rpx;
}

.price-quantity {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  font-size: 32rpx;
  color: var(--price-color);
  font-weight: bold;
}

.delete-btn {
  position: absolute;
  right: 20rpx;
  top: 20rpx;
  font-size: 40rpx;
  color: #999;
  padding: 10rpx;
}

/* 底部结算栏样式 */
.footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100rpx;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.select-all {
  font-size: 28rpx;
  color: #333;
  margin-right: 20rpx;
}

.total-box {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.price-detail {
  display: flex;
  align-items: baseline;
  font-size: 28rpx;
  color: #333;
}

.total-price {
  font-size: 36rpx;
  color: var(--price-color);
  font-weight: bold;
}

.selected-count {
  font-size: 24rpx;
  color: #999;
}

.checkout-btn {
  width: 200rpx;
  height: 80rpx;
  line-height: 80rpx;
  background: var(--primary-color);
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
  margin-left: 20rpx;
}

.checkout-btn[disabled] {
  background: #ccc;
  color: #fff;
}

.status-tag {
  font-size: 20rpx;
  padding: 2rpx 8rpx;
  border-radius: 4rpx;
  margin-left: 10rpx;
}

.off-shelf {
  background-color: #fbe9e7;
  color: #ff5722;
}

.invalid-tip {
  font-size: 24rpx;
  color: #ff5722;
}

.checkbox checkbox[disabled] {
  opacity: 0.5;
}
</style> 